package app.action;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

/**
 * Create class named: <b>AppUtilities</b> extending this class for your application
 * 
 * @author manh.vu
 */
public abstract class AbsAppUtilities {
	protected ArrayList<File> files = new ArrayList<>();
	protected FileUtilities fileUtilities;

	private File file; // for storing property file
	public static final String LAST_LOCATION = "LastLocation";
	public static final String LAST_FILENAME = "LastFileName";
	private String HEADER = "manh.vv.htth@gmail.com";

	protected Properties prop = new Properties();

	public AbsAppUtilities(File file) throws IOException {
		this.file = file;
		FileInputStream in = null;
		if(file.exists()) {
			in = new FileInputStream(file);
		}

		if(in != null && in.read() > 0) {
			prop.load(in);
		}
		else {
			this.storingPropertiesFile();
		}

		this.fileUtilities = new FileUtilities("txt", "mp3");
	}

	public ArrayList<File> getFiles() {
		return files;
	}

	public void setFiles(File dir) {
		FileFilter fileFilter = new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return fileUtilities.isAcceptable(pathname);
			}
		};

		File[] files = dir.listFiles(fileFilter);
		for(File file : files) {
			this.files.add(file);
		}
	}

	public String[] getFileName() {
		if(this.files.isEmpty()) {
			return null;
		}

		int amtOfFile = this.files.size();
		String[] listFileName = new String[amtOfFile];
		for(int i = 0; i < amtOfFile; i++) {
			listFileName[i] = "  " + this.files.get(i).getName();
		}

		return listFileName;
	}

	public FileUtilities getFileUtilities() {
		return fileUtilities;
	}

	public String getLastLocation() {
		return prop.getProperty(LAST_LOCATION);
	}

	public String getLastFileName() {
		return prop.getProperty(LAST_FILENAME);
	}

	public void storingPropertiesFile() throws IOException {
		FileOutputStream out = new FileOutputStream(this.file);
		if(!prop.isEmpty()) {
			prop.store(out, HEADER);
		}
	}

	public Properties getProp() {
		return prop;
	}

	public File getFile() {
		return file;
	}
}
